package com.bm.main;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.alibaba.druid.util.StringUtils;
import com.bm.util.Config;
import com.bm.util.ListenerMember;
import com.bm.util.ListenerTrade;
import com.bm.util.ListenerUser;
import com.bm.util.PubClient;
import com.bm.util.SubClient;

import redis.clients.jedis.JedisPubSub;

//订阅
public class JedisMain {
	private static Logger logger=LogManager.getLogger(JedisMain.class);
	//订阅发布联测
	public static  void TestPubSub() throws Exception{
			//加载配置文件
			Config config= new Config();
		    PubClient pubClient = new PubClient(config.getRedisHost(), config.getRedisPort());  
	        final String channel = config.getRedisChannelTrade();  
	        pubClient.pub(channel, "before1");  
	        pubClient.pub(channel, "before2");  
	        Thread.sleep(2000);  
	        //消息订阅着非常特殊，需要独占链接，因此我们需要为它创建新的链接；  
	        //此外，jedis客户端的实现也保证了“链接独占”的特性，sub方法将一直阻塞，  
	        //直到调用listener.unsubscribe方法  
	        Thread subThread = new Thread(new Runnable() {  
	            @Override  
	            public void run() {  
	                try{  
	                    SubClient subClient = new SubClient("192.168.0.144", 6379);  
	                    System.out.println("----------subscribe operation begin-------");  
	                    JedisPubSub listener = new ListenerTrade();  
	                    //在API级别，此处为轮询操作，直到unsubscribe调用，才会返回  
	                    subClient.sub(listener, channel);  
	                    System.out.println("----------subscribe operation end-------");  
	                }catch(Exception e){  
	                    e.printStackTrace();  
	                }  
	            }  
	        });  
	        subThread.start();  
	        int i=0;  
	        while(i < 10){  
	            String message =""+i;//apache-commons  
	            pubClient.pub(channel, message);  
	            i++;  
	            Thread.sleep(10000);  
	        }  
	        //被动关闭指示，如果通道中，消息发布者确定通道需要关闭，那么就发送一个“quit”  
	        //那么在listener.onMessage()中接收到“quit”时，其他订阅client将执行“unsubscribe”操作。  
	        pubClient.close(channel);  
	        
	        //此外，你还可以这样取消订阅  
	        //listener.unsubscribe(channel);   
	}
	
	
	//监听订阅消息
	public static void ChannelSub(String channel,JedisPubSub listener) throws Exception{
		 //加载配置文件
		 Config config= Config.getConfig();
  		 try {
			 SubClient subClient = new SubClient(config.getRedisHost(), config.getRedisPort());  
			 System.out.println("----------开始订阅【"+channel+"】频道-------");  
			 //在API级别，此处为轮询操作，直到unsubscribe调用，才会返回  
			 subClient.sub(listener, channel);  
			 System.out.println("----------订阅【"+channel+"】成功---------");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("监听【"+channel+"】频道失败:"+e.toString());
 		    logger.error("监听【"+channel+"】频道失败:"+e.toString());
		}
	}
	
	

	public static void main(String[] args) throws Exception {
		Config config= new Config();
		
		Thread threadTrade= new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					//订阅交易数据频道
					String channelTrade=config.getRedisChannelTrade();
					if(!StringUtils.isEmpty(channelTrade))
						ChannelSub(channelTrade,new ListenerTrade());
					else{
						logger.error("请配置交易数据频道，否则无法正常接收数据!!!");
						System.out.println("请配置交易数据频道，否则无法正常接收数据!!!");
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		
		Thread threadMember= new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					//订阅会员数据频道
					String channelMember=config.getRedisChannelMember();
					if(!StringUtils.isEmpty(channelMember))
						ChannelSub(channelMember,new ListenerMember());
					else{
						logger.error("请配置会员数据频道，否则无法正常接收数据!!!");
						System.out.println("请配置交易数据频道，否则无法正常接收数据!!!");
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		
		
		Thread threadUser= new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					//订阅用户数据频道
					String channelUser=config.getRedisChannelUser();
					if(!StringUtils.isEmpty(channelUser))
						ChannelSub(channelUser,new ListenerUser());
					else{
						logger.error("请配置用户数据频道，否则无法正常接收数据!!!");
						System.out.println("请配置用户数据频道，否则无法正常接收数据!!!");
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		
		threadTrade.start();
		threadMember.start();
		threadUser.start();
	}
}
